const express = require('express');//引入express框架
const app = express();//创建一个Express应用程序

//中间件引入
const createError = require('http-errors');//http错误
const path = require('path'); //路径使用
const cookieParser = require('cookie-parser'); //设置响应头
const logger = require('morgan'); //中间件记录日志
const bodyParser = require('body-parser'); // 接收post请求参数req.body
const fs = require('fs')//文件系统

//路由的引入
const indexRouter = require('./routes/index');
const preview =  require('./preview')
const api = require('./routes/api')

let date = new Date()
const log = fs.createWriteStream(`./log/${date.getFullYear()}${date.getMonth()+1}${date.getDay()}.log`, {flags : 'a'}) 

// 自定义跨域中间件
const allowCors = function(req, res, next) {
  res.header('Access-Control-Allow-Origin', req.headers.origin);//接收到域名 req.headers.origin ||*
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');//接收请求方式
  res.header('Access-Control-Allow-Headers', 'Content-Type');//接收请求头
  res.header('Access-Control-Allow-Credentials','true');// 客户端携带证书式访问
  next();
};
app.use(allowCors);
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// 前端网页渲染,使用模版引擎pug
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

//日志
app.use(logger('dev'));//日志在控制台输出
app.use(logger('combined', {stream : log})); //生成日志文件

//托管静态文件,找public文件下的文件
app.use(express.static(path.join(__dirname, 'public')));
// 路由
app.use('/', indexRouter)
app.use('/api',api)
app.use('/preview',preview)

// 找不到页面跳转404
app.use(function(req, res, next) {
  next(createError(404));
});

// 错误拦截
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};
  // 渲染错误页面
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
